package com.vegsan.taskreminder;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;


public class OnBootReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		//Log.d("OnBootReseiver", "Start!");
		ReminderManager reminderManager = new ReminderManager(context);
		ReminderDbAdapter dbHelper = new ReminderDbAdapter(context);
		dbHelper.open();
		Cursor cursor = dbHelper.fetchAllReminders();
		//Log.d("OnBootReseiver", "All records were reseived");
		if (cursor != null) {
			cursor.moveToFirst();
			Log.d("OnBootReseiver", "First position of cursor");
			int rowIdColumnIndex = cursor.getColumnIndex(ReminderDbAdapter.KEY_ROWID);
			int dateTimeColumnIndex = cursor.getColumnIndex(ReminderDbAdapter.KEY_DATE_TIME);
			
			while (cursor.isAfterLast() == false){
				Long rowId = cursor.getLong(rowIdColumnIndex);
				String dateTime = cursor.getString(dateTimeColumnIndex);
				Calendar cal = Calendar.getInstance();
				Calendar currentTime = Calendar.getInstance();
				SimpleDateFormat format = new SimpleDateFormat(ReminderEditActivity.DATE_TIME_FORMAT);
				try {
					java.util.Date date = format.parse(dateTime);
					cal.setTime(date);
					if  (cal.compareTo(currentTime)>=0){
						reminderManager.setReminder(rowId, cal);
					}
					} catch (ParseException e) {
					Log.e("OnBootReceiver", e.getMessage(), e);
					}			
				//Log.d("OnBootReseiver", "���������� ������� ��� ��������!");
				//Log.d("OnBootReseiver", "������ ������� = "+rowIdColumnIndex);
				cursor.moveToNext();
			}
			cursor.close();
		} 
		
		dbHelper.close();
	}

}
